package com.jzy.message.activities;

import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jzy.message.R;
import com.jzy.message.activities.base.AppRequestInterface;
import com.jzy.message.activities.base.BaseFragment;
import com.jzy.message.activities.base.DialogWaiting;
import com.jzy.message.control.letterlistview.LetterListView;
import com.jzy.message.util.common.CommUtility;
import com.jzy.message.util.image.ImageConfig;
import com.jzy.message.util.json.JsonUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/7/2.
 */
public class Message_ContactFragment extends BaseFragment implements View.OnClickListener  {
    private final int CMD_GETCONTACT=0X0001;
    private ListView lv_message_contact;

    private TextView overlay;

    private ImageView suspend_search;

    private LetterListView letterlv_message_view;

    private AsyncQueryHandler asyncQuery;

    private static final String NAME = "userName", NUMBER = "number",
            SORT_KEY = "userName";

    private HashMap<String, Integer> alphaIndexer;

    private String[] sections;

    public List<ContentValues> list = new ArrayList<ContentValues>();

    private WindowManager windowManager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.message_fragment_contact, container, false);
        initView(view);
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dlgWaiting = DialogWaiting.createDialogWaiting(getActivity(), "数据加载中...");
        getContact();
    }
    private void initView(View view)
    {
        lv_message_contact = (ListView) view.findViewById(R.id.lv_message_contact);
        letterlv_message_view = (LetterListView) view.findViewById(R.id.letterlv_message_view);
        letterlv_message_view.setOnTouchingLetterChangedListener(new LetterListViewListener());
        alphaIndexer = new HashMap<String, Integer>();
        windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        new OverlayThread();
        initOverlay();
        initSuSearch();
        lv_message_contact.setOnScrollListener(new AbsListView.OnScrollListener()
        {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState)
            {
                suspend_search.setVisibility(View.VISIBLE);
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount)
            {
                suspend_search.setVisibility(View.GONE);
            }
        });
        lv_message_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ListAdapter adapter=(ListAdapter)lv_message_contact.getAdapter();
                Map<String, Object> map = (Map<String, Object>)adapter.getItem(i);
                String ChatToUserName=map.get("userName").toString();
                Intent intent =new Intent(getActivity(), com.jzy.message.activities.ChatActivity.class);
                intent.putExtra("from", ChatToUserName);
                startActivity(intent);
            }
        });
        suspend_search.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
               /* ComponentName friendcName =
                        new ComponentName(Friend.this,
                                "com.example.test_intent.FriendSearch");
                Intent friend_viewIntent = new Intent();
                friend_viewIntent.setComponent(friendcName);
                startActivity(friend_viewIntent);
                Toast.makeText(getApplicationContext(), "sousuo",
                        Toast.LENGTH_LONG).show();
                // TODO Auto-generated method stub*/
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            
            default:
                break;
        }
    }
    private void initSuSearch()// 搜索
    {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        suspend_search = (ImageView) inflater.inflate(R.layout.message_fragment_contact_suspend_search, null);
        WindowManager.LayoutParams lp =
                new WindowManager.LayoutParams(80, 80, 170, -280,
                        WindowManager.LayoutParams.TYPE_APPLICATION,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);
        windowManager.addView(suspend_search, lp);
    }
    private void initOverlay()
    {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        overlay = (TextView) inflater.inflate(R.layout.message_fragment_contact_overlay, null);
        WindowManager.LayoutParams lp =
                new WindowManager.LayoutParams(
                        120,
                        120,
                        100,
                        0,
                        WindowManager.LayoutParams.TYPE_APPLICATION,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                        PixelFormat.TRANSLUCENT);
        windowManager.addView(overlay, lp);
    }
    //获取联系人
    private  void getContact()
    {
        RequestParams params = new RequestParams(AppRequestInterface.sMessageContactUrl);
        //添加参数
       // params.addQueryStringParameter("userName",userName);
        requestDataGet(CMD_GETCONTACT, getActivity(), params);
    }
    @Override
    public void ParseData(int flag,String jsonstr)
    {
        switch (flag)
        {
            case CMD_GETCONTACT:
                parseContact(jsonstr);
                break;
            default:
                break;
        }
    }
    //解析获取到的博客数据
    private void parseContact(String jsonstr)
    {
        try {
            if(!CommUtility.IsResponseCorrect(jsonstr))
            {
                CommUtility.showmsg(getActivity(),"data error");
                return;
            }
            List<LinkedHashMap<String, Object>> list;
            list= (List<LinkedHashMap<String, Object>>) JsonUtil.JSONToObj(jsonstr, List.class,"data");
            ListAdapter adapter = new ListAdapter(getActivity(), list);
            lv_message_contact.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getAlpha(String str)
    {
        if (str == null)
        {
            return "#";
        }
        if (str.trim().length() == 0)
        {
            return "#";
        }
        char c = str.trim().substring(0, 1).charAt(0);
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches())
        {
            return (c + "").toUpperCase();
        }
        else
        {
            return "#";
        }
    }
    private class LetterListViewListener implements LetterListView.OnTouchingLetterChangedListener
    {
        @Override
        public void onTouchingLetterChanged(final String s, float y, float x)
        {
            if (alphaIndexer.get(s) != null)
            {
                int position = alphaIndexer.get(s);

                lv_message_contact.setSelection(position);
                overlay.setText(sections[position]);
                overlay.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onTouchingLetterEnd()
        {
            overlay.setVisibility(View.GONE);
        }
    }
    private class OverlayThread implements Runnable
    {

        @Override
        public void run()
        {
            overlay.setVisibility(View.GONE);
        }
    }
    private class ListAdapter<T> extends BaseAdapter
    {

        private LayoutInflater inflater;

        private List<T> list;

        public ListAdapter(Context context, List<T> list)
        {
            this.inflater = LayoutInflater.from(context);
            this.list = list;
            alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];

            for (int i = 0; i < list.size(); i++)
            {
                Map<String, Object> map=(Map<String, Object>)list.get(i);
                String sUserName=map.get(SORT_KEY)==null?"":map.get(SORT_KEY).toString();
                String currentStr = getAlpha(sUserName);
                String previewStr = " ";
                if((i - 1) >= 0)
                {
                    Map<String, Object> map1=(Map<String, Object>)list.get(i-1);
                    String sUserName1=map1.get(SORT_KEY)==null?"":map1.get(SORT_KEY).toString();
                    previewStr=getAlpha(sUserName1);
                }
                if (!previewStr.equals(currentStr))
                {
                    String name = currentStr;
                    alphaIndexer.put(name, i);
                    sections[i] = name;
                }
            }
        }
        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            final ViewHolder holder;

            if (convertView == null)
            {
                convertView = inflater.inflate(R.layout.message_fragment_contact_item, null);
                holder = new ViewHolder();
                holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
                holder.tv_message_contact_name = (TextView) convertView.findViewById(R.id.tv_message_contact_name);
//                holder.number =
//                        (TextView) convertView.findViewById(R.id.number);
                holder.cv_message_contact_avatarimage=(ImageView)convertView.findViewById(R.id.cv_message_contact_avatarimage);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            Map<String, Object> map=(Map<String, Object>)list.get(position);
            //ContentValues cv = list.get(position);
            holder.tv_message_contact_name.setText(map.get(NAME)==null?"":map.get(NAME).toString());
            //holder.number.setText(cv.getAsString(NUMBER));
            String sUserName=map.get(SORT_KEY)==null?"":map.get(SORT_KEY).toString();
            String currentStr = getAlpha(sUserName);
            String previewStr =" ";
            if((position - 1) >= 0)
            {
                Map<String, Object> map1=(Map<String, Object>)list.get(position-1);
                String sUserName1=map1.get(SORT_KEY)==null?"":map1.get(SORT_KEY).toString();
                previewStr=getAlpha(sUserName1);
            }
            if (!previewStr.equals(currentStr))
            {
                holder.alpha.setVisibility(View.VISIBLE);
                holder.alpha.setText(currentStr);
            }
            else
            {
                holder.alpha.setVisibility(View.GONE);
            }
            String sUserId=map.get("userId").toString();

            String sAvatarImage = AppRequestInterface.getUserAvatarImageUrl(sUserId);//AppConfig.JsonUrl+map.get("AvatarImage").toString();
            holder.cv_message_contact_avatarimage.setImageResource(R.drawable.temp_picpeople);
            x.image().loadDrawable(sAvatarImage, ImageConfig.image_options_default, new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable drawable) {
                    holder.cv_message_contact_avatarimage.setImageDrawable(drawable);
                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {

                }
            });
            return convertView;
        }
        private class ViewHolder
        {

            TextView alpha;

            TextView tv_message_contact_name;

            ImageView cv_message_contact_avatarimage;
        }
    }
    @Override
    public void onDestroy() {
        if (windowManager != null)// 防止内存泄露
        {
            windowManager.removeView(overlay);
            windowManager.removeView(suspend_search);
        }
        super.onDestroy();
    }
}

